import tornado.web
from typing import Optional, Awaitable
import logging


class FileHandler(tornado.web.RequestHandler):

    def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
        pass

    async def post(self):
        """文件上传"""
        # logging.warning('data=', self.request)
        try:
            file_metas = self.request.files['file']
            if len(file_metas) > 0:
                for meta in file_metas:
                    filename = meta['filename']
                    filepath = "./" + filename
                    with open(filepath, 'wb') as up:
                        up.write(meta['body'])
                self.write('finished!')
            else:
                self.write('请上传文件!')
        except:
            self.write('参数有误!')

    async def get(self):
        """文件下载"""
        self.set_header('Content-Type', 'application/octet-stream')
        with open('./1.txt', 'rb') as f:
            while True:
                data = f.read(100)
                if not data:
                    break
                self.write(data)
        # 记得要finish
        self.finish()